#include "calidialog.h"
#include "ui_calidialog.h"
#include "caliparammanager.h"
#include "imageprocess.h"
#include <QFileDialog>
#include <QTextCodec>
#include  "toast.h"
#include "pgapinsdialog.h"
#include "pgalayoutmanager.h"
using namespace HalconCpp;
CaliDialog::CaliDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::CaliDialog)
{
    ui->setupUi(this);
	

    setWindowFlags(Qt::WindowCloseButtonHint | Qt::MSWindowsFixedSizeDialogHint | Qt::Dialog);

  //  m_noramlFilePath = "E:/images/1227/Pic_2019_01_04_104354_blockId#37181.bmp";

    connect(ui->pushButton_Select1, &QPushButton::clicked, [=](){
        SelectFiles();
    });

    connect(ui->pushButton_Cali1, &QPushButton::clicked, [=](){
        Cali();
    });

  //  connect(ui->pushButton_Select2, &QPushButton::clicked, [=](){
  //      SelectANormalFile();
		///*m_OKFileList = QFileDialog::getOpenFileNames(nullptr,
		//	"Select a normal pga image",
		//	"E:/images/1227/cali",
		//	"Images(*.png *.bmp *.jpg)"
		//);*/
  //  });

  //  connect(ui->pushButton_Cali2, &QPushButton::clicked, [=](){
  //      Cali2();
  //  });

}

CaliDialog::~CaliDialog()
{
    delete ui;
}

void CaliDialog::SelectFiles()
{
    m_fileList = QFileDialog::getOpenFileNames(nullptr,
                                               "Select images",
                                               "E:/images/1227/cali",
                                               "Images(*.png *.bmp *.jpg)"
                                               );



}

void CaliDialog::SelectANormalFile()
{
    m_noramlFilePath = QFileDialog::getOpenFileName(nullptr,
                                                    "Select images",
                                                    "E:/images/1227/",
                                                    "Images(*.png *.bmp *.jpg)"
                                                    );

}

QList<QPoint> CaliDialog::GetStdPoints(QString path)
{
	QList<QPoint> list;
	bool bFileIsImage = true;
	QFileInfo file(path);

	if (!file.exists())
	{
		bFileIsImage = false;
		return list;
	}

	QPixmap pixs;
	pixs.load(path);
	if ((pixs.isNull()))
	{
		bFileIsImage = false;

	}

	
	if (bFileIsImage)
	{
		QTextCodec *code = QTextCodec::codecForName("GB2312");

		std::string name = code->fromUnicode(path).data();
		HTuple FileName = HTuple(name.data());

		HImage ho_Image;
		ReadImage(&ho_Image, FileName);

		//useless todo
	//	list = ImageProcess::getInstance()->GetICStdPos(ho_Image);
		
	}
	/*else {

		Toast *t = new Toast(this, tr("File error"), 180, 30);
		t->toast();
	}*/
	return list;
}


void CaliDialog::Cali2()
{
	QList<QPoint> listMean = GetStdPoints(m_noramlFilePath);

	//listMean.clear();
	//QList<QList<QPoint>>ll =  PgaLayoutManager::getInstance()->GetDefaultPinsParam();
	//for each (QList<QPoint> l in ll)
	//{
	//	listMean.append(l);
	//}

	PgaPinsDialog *dlg = new PgaPinsDialog(this, listMean);
	dlg->exec();

}

void CaliDialog::Cali()
{
    HObject  ho_Caltab, ho_Circles;

    // Local control variables
    HTuple  hv_StartCamPar, hv_CalibDataID, hv_CaltabName;
    HTuple  hv_ImageFiles, hv_Row, hv_Column;
    HTuple  hv_Pose, hv_Errors, hv_CamParam, hv_CameraType;
    HTuple  hv_CalobjPose;

    hv_StartCamPar.Clear();
    hv_StartCamPar[0] = 0.016;
    hv_StartCamPar[1] = 0;
    hv_StartCamPar[2] = 0.00000345;
    hv_StartCamPar[3] = 0.00000345;
    hv_StartCamPar[4] = 1224;
    hv_StartCamPar[5] = 1024;
    hv_StartCamPar[6] = 2448;
    hv_StartCamPar[7] = 2048;
    CreateCalibData("calibration_object", 1, 1, &hv_CalibDataID);
    SetCalibDataCamParam(hv_CalibDataID, 0, "area_scan_telecentric_division", hv_StartCamPar);
    QString dir_str = QString("%1/Config/7_7.descr").arg(QCoreApplication::applicationDirPath());
	QFileInfo info(dir_str);
	if (!info.exists())
	{
		Toast *t = new Toast(this, tr("File(7_7.descr) not exist"), 280, 30);
		t->toast();
		return;
	}

    hv_CaltabName = dir_str.toStdString().c_str();
    SetCalibDataCalibObject(hv_CalibDataID, 0, hv_CaltabName);
	if (!m_fileList.count())
	{
		Toast *t = new Toast(this, tr("Please select images"), 280, 30);
		t->toast();
		return;
	}
    for (int i = 0; i < m_fileList.count(); ++i) {
        QString path = m_fileList.at(i);
        QFileInfo file(path);
        if(file.exists() == false)
        {
            continue;
        }

        QTextCodec *code = QTextCodec::codecForName("GB2312");

        std::string name = code->fromUnicode(path).data();
        HTuple FileName = HTuple(name.data());

        HImage ho_Image;
        ReadImage(&ho_Image, FileName);
        HObject ho_CalPlate;
        // FindCaltab(ho_Image, &ho_CalPlate, hv_CaltabName, 3, 112, 5);

        if(ho_Image.IsInitialized())
        {
            HTuple hv_Index1;
            FindCalibObject(ho_Image, hv_CalibDataID, 0, 0, i, HTuple(), HTuple());
            GetCalibDataObservContours(&ho_Caltab, hv_CalibDataID, "caltab", 0, 0, i);
            GetCalibDataObservPoints(hv_CalibDataID, 0, 0, i, &hv_Row, &hv_Column,
                                     &hv_Index1, &hv_Pose);
        }

        // GenCircle(&ho_Circles, hv_Row, hv_Column, HTuple(hv_Row.TupleLength(),2.0));
    }
    CalibrateCameras(hv_CalibDataID, &hv_Errors);
    GetCalibData(hv_CalibDataID, "camera", 0, "params", &hv_CamParam);
    //  GetCalibData(hv_CalibDataID, "camera", 0, "type", &hv_CameraType);

    GetCalibData(hv_CalibDataID, "calib_obj_pose", (HTuple(0).Append(0)), "pose", &hv_CalobjPose);

    CaliParamManager::getInstance()->SaveCaliParam(hv_CamParam, hv_CalobjPose);
    hv_CamParam = CaliParamManager::getInstance()->GetCameraParam();
    hv_CalobjPose = CaliParamManager::getInstance()->GetPoseParam();


    HTuple hv_X1, hv_Y1, hv_Distance;
    int v1 = 00;
    int v2 = 2448;
    ImagePointsToWorldPlane(hv_CamParam, hv_CalobjPose, HTuple(0).Append(0), HTuple(v1).Append(v2), "mm",&hv_X1, &hv_Y1);
    DistancePp(hv_Y1.TupleSelectRange(0,(hv_Y1.TupleLength())-2), hv_X1.TupleSelectRange(0,(hv_X1.TupleLength())-2),
               hv_Y1.TupleSelectRange(1,(hv_Y1.TupleLength())-1), hv_X1.TupleSelectRange(1,(hv_X1.TupleLength())-1),
               &hv_Distance);

	qDebug() << "cali 2448 =" << hv_Distance.D()<<"mm";
    if (hv_Distance.D()>=50 && hv_Distance.D()<=55 )
    {
        Toast *t = new Toast(this, tr("Calibrate success"), 180, 30);
        t->toast();
    }
    else {
        Toast *t = new Toast(this, tr("Calibrate fail"),180, 30);
        t->toast();
    }

}
